package ru.kradef.eclipse.plugin;

import java.util.List;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.core.model.ILaunchConfigurationDelegate;

/**
 * The Composite launch delegate.
 * 
 * @see MainCompositeLaunchConfigurationTab
 *
 * @author D. Kranchev, kradef@gmail.com
 * @since 04.06.2012
 */
public class LaunchConfigurationTypeDelegate implements
	ILaunchConfigurationDelegate {

    @Override
    public void launch(ILaunchConfiguration configuration, String mode,
	    ILaunch launch, IProgressMonitor monitor) throws CoreException {
	List configurationNameList = configuration
		.getAttribute(
			MainCompositeLaunchConfigurationTab.SELECTED_CONFIGURATION_LIST,
			(List) null);
	if (configurationNameList == null) {
	    return;
	}

	// todo: will be nice to add new control element on the config tab for
	// sequential execution of launches (wait before launch next config)
	ILaunchManager launchManager = DebugPlugin.getDefault()
		.getLaunchManager();
	ILaunchConfiguration[] launchConfigurations = launchManager
		.getLaunchConfigurations();
	monitor.beginTask("Launching composite's tasks",
		launchConfigurations.length);
	int n = 0;
	for (ILaunchConfiguration config : launchConfigurations) {
	    if (monitor.isCanceled()) {
		break;
	    }
	    // the launch order is not supported
	    if (configurationNameList.contains(config.getName())) {
		config.launch(mode, new SubProgressMonitor(monitor, 10));
		monitor.subTask("Launching [" + config.getName()
			+ "] is complete");
		monitor.worked(++n);
	    }
	}
	monitor.done();
    }

}
